<template>
   <div class="app-container">
    <el-form ref="form" :model="form" :rules="formRules" label-width="120px" size="medium">
      <el-form-item label="员工姓名" prop="username">
        <el-input v-model="form.username" style="width:300px" />
      </el-form-item>
      <el-form-item label="员工工号" prop="workNum">
        <el-input v-model="form.workNum" style="width:300px" @blur="testExist" />
      </el-form-item>
      <el-form-item label="员工角色" prop="roleId">
        <el-select v-model="form.roleId" placeholder="请选择该员工当前角色" @focus="getRoleInfo" style="width:300px">
          <el-option :value="item.roleId" :label="item.roleName" v-for="(item,index) of this.roleList.data" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="员工短号">
        <el-input v-model="form.shortNum" style="width:300px" />
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="form.phone" maxlength="11" style="width:300px" />
      </el-form-item>
      <el-form-item label="隶属部门" prop="departmentName">
        <el-select v-model="form.departmentName" placeholder="请选择该员工当前所在部门" @focus="getDepartInfo" style="width:300px">
          <el-option :value="item" :label="item" v-for="(item,index) in this.departList.data" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="上级领导工号" prop="parentNumber">
        <el-input v-model="form.parentNumber" style="width:300px" />
      </el-form-item>
      <el-form-item label="入职时间" prop="entryTime">
          <el-date-picker v-model="form.entryTime" @blur="checkEntryTime" editable format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间" style="width:300px" />
      </el-form-item>
      <el-form-item label="新员工标识" prop="newEmployee">
        <el-switch v-model="form.newEmployee" active-value="1" inactive-value="0" active-text="新员工" inactive-text="老员工" />
      </el-form-item>
      <el-form-item label="员工岗位职级">
        <el-cascader v-model="form.jobClassStr" separator="-" :options="options" clearable filterable />
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-switch v-model="form.status" active-value="1" inactive-value="0" active-text="启用" inactive-text="停用" /> 
      </el-form-item>
      <el-form-item label="员工头像上传">
        <el-upload
          class="avatar-uploader"
          action="http://192.168.120.43:8086/portraitUploadFile"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :data="upPictureData"
          :headers="upPictureHeader"
          :before-upload="beforeAvatarUpload">
          <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { parseTime,parseTimeYYDD,getTimeHMS } from '@/utils'
import { getList,addWorker,updateManager,updateIsFlag,updatePassword,getDepartment,getRoleList,getDepartList,testWorkNum } from '@/api/user'
import { validatePhone, validateChineseName, validateNum} from '@/utils/validate'
import BackToTop from "@/components/BackToTop";
import VePie from "v-charts/lib/pie";


export default {
 inject: ['reload'],
 data() {
  //  对用户输入手机号码进行校验
  //  var validateuserPhone = (rule, value, callback) => {
  //    if (value === '') {
  //      callback(new Error('电话号码不能为空'))
  //    }
  //    setTimeout(() => {
  //      if (validatePhone(value)) {
  //        callback()
  //      }else {
  //        callback(new Error('请填写正确的手机号码'))
  //      }
  //    }, 500)
  //  }
   //  对用户输入工号与短号进行校验进行校验
   var validateNumber = (rule, value, callback) => {
     if (value === '') {
       callback(new Error('数据不能为空'))
     }
     setTimeout(() => {
       if (validateNum(value)) {
         callback()
       }else {
         callback(new Error('请填写正确的数据'))
       }
     }, 1000)   
   }
   //  对用户输入姓名进行校验进行校验，仅限中文姓名
   var validateuserName = (rule, value, callback) => {
     if (value === '') {
       callback(new Error('员工姓名不能为空'))
     }
     setTimeout(() => {
       if (validateChineseName(value)) {
         callback()
       }else {
         callback(new Error('请输入中文'))
       }
     }, 1000)
   }
    return {
      form: {
        username: '',
        roleId: '',
        workNum: '',
        shortNum: '',
        jobClassStr: '',
        parentNumber: '',
        phone: '',
        departmentName: '',
        entryTime: '',
        status: false,
        imageUrl: '',
        newEmployee: false
      },
      // 接受来自list页面传过来的数据
      getItem: null,
      // 从级联选择器获取到的数据以对象的形式暂时存放在grade当中
      grade: [],
      departList: {},
      upPictureHeader: { CHECK_USER_VALUE: 'GOLWAY', CHECK_PASSWORD_VALUE: '8D4DD3F80CEB6149329FDBD590B164F1' },
      upPictureData: { jobNumber: '', file: '' },
      // 从服务器调取的参数放入该对象当中
      roleList: {},
      // 表单的验证项
      formRules: {
        // phone: [{ required: false, validator: validateuserPhone, trigger: 'blur' }],
        // shortNum: [{ required: false, validator: validateNumber, trigger: 'blur' }],
        workNum: [{ required: true,validator: validateNumber, trigger: 'blur' }],
        username: [{ required: true, validator: validateuserName, trigger: 'blur' }],
        parentNumber: [{ required: true, validator: validateNumber, trigger: 'blur' }],
        roleId: [{ required: true }],
        departmentName: [{required: true}],
        newEmployee: [{required: true}],
        status: [{required: true}],
        entryTime: [{required: true}]
      },
      // 岗位职级下拉选项
      options: [{
        value: 'O1',
        label: 'O1',
        children: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }]
      }, {
        value: 'O2',
        label: 'O2',
        children: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }]
      }, {
        value: 'O3',
        label: 'O3',
        children: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }]
      },  {
        value: 'O4',
        label: 'O4',
        children: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }]
      }, {
        value: 'O5',
        label: 'O5',
        children: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }]
      }]
    }
 },  
  methods: {
    handleClass(value) {
      let first = value.substr(0,2)
      let second = value.substr(3)
      this.grade[0] = first
      this.grade[1] = second
      console.log(this.grade)
    },
    // 对list界面传来的entryTime时间进行处理
    handleTime(value) {
      let timeString = value.substr(0,10)
      let data = new Date(timeString)
      let dealTime = data.getTime()
      console.log(dealTime)
      return dealTime
    },
    // 该函数用于检查修改员工入职时间是否修改成功，后期可以删除
    checkEntryTime() {
      console.log(this.form.entryTime)
    },
    checkJobClass() {
      console.log(this.grade)
      console.log(this.form.jobClassStr)
    },
    // 将当前输入的工号传递到后台系统，验证改工号是否已经被注册
    async testExist() {
      const { data } = await testWorkNum({ jobNumber: this.form.workNum })
      console.log(res)
    },
    // 获取角色列表函数,当选择器框获得焦点时触发,从服务器调取参数
    async getRoleInfo() {
      try {
        this.roleList = await getRoleList()
        console.log(this.roleList.data)
        console.log(this.roleList)
      } catch (err) {}
    },
    // 获取部门函数
    async getDepartInfo() {
     try {
        this.departList = await getDepartList()
        console.log(this.departList.data)
      } catch (err) {}
    },
    // "提交"按钮
    async onSubmit() {
      let query = {
        departmentName: this.form.departmentName,
        userName: this.form.username,
        phone: this.form.phone,
        jobNumber: this.form.workNum,
        roleId: this.form.roleId,
        entryTime: this.form.entryTime,
        status: this.form.status,
        newEmployee: this.form.newEmployee,
        parentNumber: this.form.parentNumber,
        imageUrl: this.form.imageUrl,
        jobClassStr: this.form.jobClassStr.join('-'),
        shortNumber: this.form.shortNum
      }
      try{
        const { data } = await addWorker(query)
        this.$message({
          type: 'success ',
          message: `提交成功`
        })
      }catch(e){}
    },
    // "取消"按钮
    onCancel() {  
      console.log('bye')
    },
    // 用户头像上传成功之后的触发函数
    handleAvatarSuccess(res,file) {
      console.log(res)
      console.log(file.response.results)
      this.form.imageUrl = res.results+ '?d=' + Date.now();
      console.log(this.form.imageUrl)
      console.log(this.form.workNum)
      const _self = this
      let jobNumber = this.form.workNum
      let imageUrl = this.form.imageUrl
      console.log(jobNumber)
      console.log(imageUrl)
      _self.upPictureData.jobNumber = jobNumber
      _self.upPictureData.file = imageUrl
      console.log(_self.upPictureData)
        this.$message({ 
          message: '用户图像上传成功',
          type: 'success'
        }) 
    },
    // 用户头像上传之前判断函数，格式限制为JPG，大小小于2M
    // const声明一个只读的常量。一旦声明，常量的值就不能改变。且只在声明所在的块级作用域内有效
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M;
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>